package com.jms.logger.controller;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jms.logger.po.LoggerInfo;
import com.jms.logger.service.LoggerService;

@Controller
public class LoggerController {
	
	@Resource(name="loggerService")
	private LoggerService loggerService;
	@Resource(name="pooledConnectionFactory")
	private PooledConnectionFactory factory;
	@Resource(name="queueDestination")
	private ActiveMQQueue queue;
	
	@RequestMapping(name="/showLogger")
	public String showLogger(HttpServletRequest request,HttpServletResponse response,Model model) throws Exception {
		/**
		 * 1、查看队列中是否存在数据
		 * 2、如果有数据就添加在库中
		 * 3、显示所有的数据
		 */
		Connection connection = factory.createConnection();
		connection.start();
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		MessageConsumer consumer = session.createConsumer(queue);
		TextMessage message = (TextMessage) consumer.receive();
		
		String json_string = message.getText();
		
		if(json_string==null || json_string.equals("")) {
			model.addAttribute("lists", loggerService.showLogger());
			
			consumer.close();
			session.close();
			connection.close();
			
			return "show/showLogger";
		} else {
			/**
			 * 如果队列中有数据就取出数据
			 */
			LoggerInfo loggerInfo = new LoggerInfo();
			JSONObject json = new JSONObject(json_string);
			
			loggerInfo.setIp(json.getString("ip"));
			loggerInfo.setName(json.getString("name"));
			loggerInfo.setPswd(json.getString("pswd"));
			loggerInfo.setTimestamp(json.getString("timestamp"));
			
			loggerService.addLogger(loggerInfo);
			model.addAttribute("lists", loggerService.showLogger());
			
			consumer.close();
			session.close();
			connection.close();
			
			return "show/showLogger";
		}
		
	}
}
